package com.kly.cashmall.framework.module;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.kly.cashmall.R;
import com.kly.cashmall.framework.base.AbstractPresenterActivity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public abstract class BaseActivity extends AbstractPresenterActivity implements Toolbar.OnMenuItemClickListener {

  /**
   * 是否要有黑色底色
   */
  protected boolean darkMode() {
    return false;
  }

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setView(savedInstanceState);
    loadData();

  }

  @Override public final void setContentView(@LayoutRes int layoutResID) {
    setContentView(onReplaceRootView(layoutResID));
  }

  @Override public void setContentView(View view) {
    super.setContentView(view);
    if (darkMode()) {
      try {

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * 使用R.layout.base_content_view 替换根布局
   */
  protected View onReplaceRootView(@LayoutRes int layoutResID) {
    ViewGroup rootView = (ViewGroup) LayoutInflater.from(this)
            .inflate(R.layout.activity_base_content_view, null);
    View.inflate(this, layoutResID,
        rootView.findViewById(R.id.content_container));
    return rootView;
  }

  protected abstract void setView(@Nullable Bundle savedInstanceState);

  protected abstract void loadData();

  @Override public void onResume() {
    super.onResume();
  }

  @Override public void onPause() {
    super.onPause();
  }

  private transient boolean isActivityDestroyed = false;

  public boolean isActivityDestroyed() {
    return isActivityDestroyed;
  }

  @Override protected void onDestroy() {
    super.onDestroy();
    isActivityDestroyed = true;
  }

  @Override public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
      View v = getCurrentFocus();
      if (isShouldHideInput(v, ev)) {

        InputMethodManager imm =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
          imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
      }
      return super.dispatchTouchEvent(ev);
    }
    // 必不可少，否则所有的组件都不会有TouchEvent了
    if (getWindow().superDispatchTouchEvent(ev)) {
      return true;
    }
    return onTouchEvent(ev);
  }

  @Override public void onBackPressed() {
    if (processBackPressed()) {
      return;
    }
    super.onBackPressed();
  }

  /**
   * process the return back logic
   * return true if back pressed event has been consumed and should stay in current view
   */
  protected boolean processBackPressed() {
    return false;
  }

  private boolean isShouldHideInput(View v, MotionEvent event) {
    if (v != null && (v instanceof EditText)) {
      int[] leftTop = { 0, 0 };
      //获取输入框当前的location位置
      v.getLocationInWindow(leftTop);
      int left = leftTop[0];
      int top = leftTop[1];
      int bottom = top + v.getHeight();
      int right = left + v.getWidth();
      // 点击的是输入框区域，保留点击EditText的事件
      return !(event.getX() > left)
          || !(event.getX() < right)
          || !(event.getY() > top)
          || !(event.getY() < bottom);
    }
    return false;
  }

  @Override public boolean onMenuItemClick(MenuItem item) {
    return false;
  }

  private Method noteStateNotSavedMethod;
  private Object fragmentMgr;
  private String[] activityClassName = { "Activity", "FragmentActivity" };

  @Override protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    invokeFragmentManagerNoteStateNotSaved();
  }

  private void invokeFragmentManagerNoteStateNotSaved() {
    //java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
      return;
    }
    try {
      if (noteStateNotSavedMethod != null && fragmentMgr != null) {
        noteStateNotSavedMethod.invoke(fragmentMgr);
        return;
      }
      Class cls = getClass();
      do {
        cls = cls.getSuperclass();
      } while (!(activityClassName[0].equals(cls.getSimpleName()) || activityClassName[1].equals(
              cls.getSimpleName())));

      Field fragmentMgrField = prepareField(cls, "mFragments");
      if (fragmentMgrField != null) {
        fragmentMgr = fragmentMgrField.get(this);
        noteStateNotSavedMethod = getDeclaredMethod(fragmentMgr, "noteStateNotSaved");
        if (noteStateNotSavedMethod != null) {
          noteStateNotSavedMethod.invoke(fragmentMgr);
        }
      }
    } catch (Exception ignore) {
    }
  }

  private Field prepareField(Class<?> c, String fieldName) throws NoSuchFieldException {
    while (c != null) {
      try {
        Field f = c.getDeclaredField(fieldName);
        f.setAccessible(true);
        return f;
      } finally {
        c = c.getSuperclass();
      }
    }
    throw new NoSuchFieldException();
  }

  private Method getDeclaredMethod(Object object, String methodName, Class<?>... parameterTypes) {
    for (Class<?> clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
      try {
        Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
        return method;
      } catch (Exception ignore) {
      }
    }
    return null;
  }
}
